<template>
    <div class="event-wrapper">
        <DataGrid
            :auto-load="autoLoad"
            border
            ref="dataGridRef"
            @selection-change="handleSelectionChange"
            showSelection
        >
            <template #toolbar-search>
                <div class="query-from-box">
                    <el-form :model="queryData">
                        <el-form-item>
                            <el-input v-model="queryData.eventName" placeholder="事件名称/标识符" clearable />
                        </el-form-item>
                        <el-form-item>
                            <el-select v-model="queryData.eventType" placeholder="触发时机" clearable>
                                <el-option v-for="(value, key) in EventType" :label="value" :key="key" :value="key" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-select v-model="queryData.actionsExecutionType" placeholder="执行类型" clearable>
                                <el-option
                                    v-for="(value, key) in ActionsExecutionType"
                                    :label="value"
                                    :key="key"
                                    :value="key"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-select v-model="queryData.eventAction" placeholder="执行方式" clearable>
                                <el-option v-for="(value, key) in EventAction" :label="value" :key="key" :value="key" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
            </template>
            <template #toolbar-operation>
                <el-button type="primary" @click="onCreateEdit()">新建</el-button>
                <el-button
                    type="primary"
                    :disabled="disabledTableSelectId && disabledTableSelectId.length ? false : true"
                    @click="onEnable({ id: disabledTableSelectId })"
                >
                    启用
                </el-button>
                <el-button
                    type="primary"
                    :disabled="enabledTableSelectId && enabledTableSelectId.length ? false : true"
                    @click="onDisable({ id: enabledTableSelectId })"
                >
                    停用
                </el-button>
            </template>
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="displayName" label="事件名称" show-overflow-tooltip>
                <template #default="{ row }">
                    <el-link type="primary" :underline="false" @click="onViewItem(row)">{{ row.displayName }}</el-link>
                </template>
            </el-table-column>
            <el-table-column prop="eventName" label="标识符" show-overflow-tooltip />
            <el-table-column label="触发时机">
                <template #default="scope">
                    <template v-if="scope.row.eventType">
                        <span v-for="(item, i) in scope.row.eventType.split(',')" :key="i">
                            {{ i ? '，' : '' }}{{ EventType[item] }}
                        </span>
                    </template>
                </template>
            </el-table-column>
            <el-table-column label="执行类型">
                <template #default="scope">
                    {{ ActionsExecutionType[scope.row.actionsExecutionType] }}
                </template>
            </el-table-column>
            <el-table-column label="执行方式">
                <template #default="scope">
                    {{ EventAction[scope.row.eventAction] }}
                </template>
            </el-table-column>
            <el-table-column label="状态" width="65">
                <template #default="scope">
                    <span class="table-item-status" :status="EnableStatus[scope.row.enableStatus]">
                        {{ EnableStatus[scope.row.enableStatus] }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="135">
                <template #default="scope">
                    <el-button link type="primary" v-if="scope.row.enableStatus" @click="onDisable(scope.row)">
                        停用
                    </el-button>
                    <template v-else>
                        <el-button link type="primary" @click="onCreateEdit(scope.row)">修改</el-button>
                        <el-button link type="primary" @click="onEnable(scope.row)">启用</el-button>
                        <el-button link type="danger" @click="onDel(scope.row)"> 删除 </el-button>
                    </template>
                </template>
            </el-table-column>
        </DataGrid>
    </div>
</template>
<script setup lang="ts">
import { modelBusinessService } from '@great/services';
import { EventType, ActionsExecutionType, EventAction } from '@/utils/constant';
import { DataGrid, type DataGridInstance } from '@great/components';
import { showPopupBox } from '@great/utils';
import EventFormModal from './EventFormModal.vue';

enum EnableStatus {
    true = '启用',
    false = '停用'
}

const props = defineProps<{
    detailData?: Record<string, any>;
}>();
const attributeTypeList = inject<any>('AttributeTypeList');
// 查询条件
const queryData = ref({
    objectName: props.detailData?.objectName,
    eventName: null,
    eventType: null,
    actionsExecutionType: null,
    eventAction: null
});
const dataGridRef = useTemplateRef<DataGridInstance>('dataGridRef');
const autoLoad = reactive({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async (current, size) => {
        const res = await modelBusinessService.event.getList({
            current,
            size,
            ...queryData.value,
            ruleName: queryData.value.eventName || null
        });
        return { data: res.data.records, total: res.data.total };
    }
});

// 表格勾选数据
const tableSelect = ref<unknown[]>([]);
const enabledTableSelectId = ref<string[]>([]); // 启用的数据
const disabledTableSelectId = ref<string[]>([]); //禁用的数据
// 表格勾选
const handleSelectionChange = (val: unknown[]) => {
    tableSelect.value = val;
    enabledTableSelectId.value = [];
    disabledTableSelectId.value = [];
    val.forEach((item: any) => {
        if (item.enableStatus) {
            enabledTableSelectId.value.push(item.id);
        } else {
            disabledTableSelectId.value.push(item.id);
        }
    });
};
// 查看
const onViewItem = (row: Record<string, any>) => {
    showPopupBox(EventFormModal, {
        row,
        attributeTypeList,
        detailData: props.detailData as Record<string, any>
    });
};
// 新增/编辑
const onCreateEdit = (row?: Record<string, any>) => {
    showPopupBox(EventFormModal, {
        row,
        detailData: props.detailData as Record<string, any>,
        attributeTypeList,
        callBack: dataGridRef.value?.refresh
    });
};
// 删除
const onDel = (row: { id: number; displayName: string }) => {
    ElMessageBox.confirm(`是否确认删除规则 ${row.displayName} ？`, '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await modelBusinessService.event.del(row.id);
            ElNotification({
                title: '删除成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
// 停用
const onDisable = async (row: { id: string | string[]; displayName?: string }) => {
    ElMessageBox.confirm(`确认停用事件${row.displayName || ''}？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await modelBusinessService.event.activation({
                ids: Array.isArray(row.id) ? row.id : [row.id],
                enabled: false
            });
            ElNotification({
                title: '停用成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
// 启用
const onEnable = async (row: { id: string | string[]; displayName?: string }) => {
    ElMessageBox.confirm(`确认将启用事件${row.displayName || ''}？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await modelBusinessService.event.activation({
                ids: Array.isArray(row.id) ? row.id : [row.id],
                enabled: true
            });
            ElNotification({
                title: '启用成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
</script>
<style scoped lang="scss">
.event-wrapper {
    .query-from-box {
        display: flex;
        align-items: center;
        .el-form {
            display: flex;
            .el-form-item {
                margin-bottom: 0;
                width: 192px;
            }
            .el-form-item + .el-form-item {
                margin-left: 10px;
            }
        }
    }
    :deep(.data-grid) {
        .table-item-tag {
            display: flex;
            justify-content: center;
        }
        .table-item-status {
            display: flex;
            align-items: center;
            &::before {
                content: '';
                width: 6px;
                height: 6px;
                display: inline-block;
                border-radius: 50%;
                margin-right: 5px;
                background-color: #e6a23c;
            }
        }
        .table-item-status[status='停用'] {
            &::before {
                background-color: #909399;
            }
        }
        .table-item-status[status='启用'] {
            &::before {
                background-color: #67c23a;
            }
        }
    }
}
</style>
